package cn.yh.producer.message;

import cn.yh.producer.model.OrderExt;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class ProducerSample {
    @Autowired
    public RocketMQTemplate rocketMQTemplate;
    public void sendSyncMsg(String topic,String Message ){
        rocketMQTemplate.syncSend(topic,Message);
    }
    public void sendASyncMsg(String topic,String Message ){
        rocketMQTemplate.asyncSend(topic, Message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult.getSendStatus());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }
    public void sendObjectMsg(String topic, OrderExt orderExt){
        rocketMQTemplate.convertAndSend(topic,orderExt);
    }

    public void sendMSGByJSONDelay(String topic,OrderExt orderExt){
        Message<OrderExt> message = MessageBuilder.withPayload(orderExt).build();
        rocketMQTemplate.syncSend(topic, message, 5000, 3);

        System.out.printf("send msg : %s",orderExt);
    }
    public void sendAsyncMsgByJsonDelay(String topic, OrderExt orderExt) throws JsonProcessingException, RemotingException, InterruptedException, MQClientException {
        //消息内容将orderExt转为json
        String json = rocketMQTemplate.getObjectMapper().writeValueAsString(orderExt);
        org.apache.rocketmq.common.message.Message message = new org.apache.rocketmq.common.message.Message(topic, json.getBytes(StandardCharsets.UTF_8));
        //设置延迟等级
        message.setDelayTimeLevel(3);
        //发送异步消息
        rocketMQTemplate.getProducer().send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }



}
